/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package frm.billingAndPaymentProcessing.managedbean;

import commonInfrastructure.accountManagement.session.EmailSessionBean;
import frm.billingAndPaymentProcessing.entity.DunningEmailEntity;
import frm.billingAndPaymentProcessing.entity.InvoiceEntity;
import frm.billingAndPaymentProcessing.session.DunningEmailSessionBean;
import frm.billingAndPaymentProcessing.session.InvoiceSessionBean;
import java.io.IOException;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author xhx
 */
@ManagedBean
@RequestScoped
public class CommenceDunningProcessManagedBean implements Serializable {

    private Long invoiceId;
    private InvoiceEntity invoice;
    private DunningEmailEntity dunningEmail;
    private String content;
    @EJB
    InvoiceSessionBean invoiceSessionBean;
    @EJB
    DunningEmailSessionBean dunningEmailSessionBean;
    @EJB
    EmailSessionBean emailSessionbean;

    /** Creates a new instance of CommenceDunningProcessManagedBean */
    public CommenceDunningProcessManagedBean() {
        dunningEmail = new DunningEmailEntity();
    }

    public void initView(PhaseEvent envet) {
        if (invoice == null) {
            setInvoice((InvoiceEntity) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("invoice"));
        }
        invoiceId = invoice.getId();
    }

    public void createDunningEmail() throws IOException {
        invoice = invoiceSessionBean.getInvoiceById(invoiceId);
        if (checkInvoice(invoice)) {
            HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
            Long employeeId = (Long) request.getSession().getAttribute("userId");
            dunningEmail.setCommencedBy(employeeId);
            dunningEmail.setSendDate(Calendar.getInstance().getTime());
            dunningEmail.setContent(convertPattern(dunningEmail.getPatternId()));
            content = setinitContent(dunningEmail, invoice);
            Calendar daysLater = Calendar.getInstance();
            daysLater.add(Calendar.DAY_OF_MONTH, 28);
            Date dueDate = daysLater.getTime();
            dunningEmail.setDueDate(dueDate);
            int dunningLevel = dunningEmail.getPatternId() % 10;
//            if(dunningLevel >= 4){
//                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "4 Dunning Emails Has Been Sent to Customer, Please make phone call to them", ""));
//                return;
//            }
            dunningEmail.setDunningLevel(dunningLevel);
            dunningEmail.setInvoice(invoice);
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("invoice", invoice);
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("content", content);
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("dunningEmail", dunningEmail);
            FacesContext.getCurrentInstance().getExternalContext().redirect("manageDunningEmail.xhtml");
        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "The Invoice Has been cleaned, Please check whether you choosed the correct Invoice ", ""));
            return;
        }
    }

    private String convertPattern(int patternId) {
        String output = null;
        if (patternId == 1) {
            output = "First Reminder For Not Paid";
        }
        if (patternId == 2) {
            output = "Second Reminder For Not Paid";
        }
        if (patternId == 11) {
            output = "First Reminder For Uncomplete Payment";
        }
        if (patternId == 12) {
            output = "First Reminder For Uncomplete Payment";
        }
        if (patternId == 3) {
            output = "Last Call";
        }
        return output;
    }

    private String setinitContent(DunningEmailEntity dunningEmail, InvoiceEntity invoice) {
        String fillContent = null;
        if (dunningEmail.getPatternId() == 0) {
            fillContent = null;
        }
        if (dunningEmail.getPatternId() == 1) {
            fillContent = "<p>Dear Customer " + invoice.getDeliveryOrder().getParentSalesOrder().getCustomer().getName() + ":</p> <p>This is a dunning email for your Bill : " + invoice.getId() + "</p> <p> We are writing this letter to call your attention to the above referenced overdue account with us. As you are aware our 'Terms of Sale' are Net 30 days and we are still anxiously awaiting your payment.\n If you wish to discuss any issues please call the undersigned immediately otherwise we look forward to getting paid at the earliest.Please ensure that payment of $" + invoice.getPayment_balance() + " reaches us.</p> <p>Thanks for Having Business with us! </p> \n\n\n Your Sincerely, \n MerlionFood Limited";
        }
        if (dunningEmail.getPatternId() == 2) {
            fillContent = "<p>Dear Customer " + invoice.getDeliveryOrder().getParentSalesOrder().getCustomer().getName() + ":</p> <p>This is a dunning email for your Bill : " + invoice.getId() + "</p> <p>For your information, This is the Second Reminder</p><p> We are writing this letter to call your attention to the above referenced overdue account with us. As you are aware our 'Terms of Sale' are Net 30 days and we are still anxiously awaiting your payment.\n If you wish to discuss any issues please call the undersigned immediately otherwise we look forward to getting paid at the earliest.Please ensure that payment of $" + invoice.getPayment_balance() + " reaches us.</p> <p>Thanks for Having Business with us! </p> \n\n\n Your Sincerely, \n MerlionFood Limited";
        }
        if (dunningEmail.getPatternId() == 11) {
            fillContent = "<p>Dear Customer " + invoice.getDeliveryOrder().getParentSalesOrder().getCustomer().getName() + ":</p> <p> This is a dunning email for your Bill : " + invoice.getId() + "</p> <p>Thanks, we have been received the payment from you previously </p> <p> However, we are writing this letter to you because we found the payment you made is not complete, please ensure the rest of the payment of $ " + invoice.getPayment_balance() + " will reach us within 30 days. </p> <p> If you have doubt with your bill and payment, Please contatct us \n\n Thanks For having Business With Us!</p> <p> \n\nYour Sincerely, \n MerlionFood Limited";
        }
        if (dunningEmail.getPatternId() == 12) {
            fillContent = "<p>Dear Customer " + invoice.getDeliveryOrder().getParentSalesOrder().getCustomer().getName() + ":</p> <p> This is a dunning email for your Bill : " + invoice.getId() + "</p> <p></p>This is the second reminder for your uncomplete payment<p> We have been received the payment from you previously </p> <p> However, we are writing this letter to you because we found the payment you made is not complete, please ensure the rest of the payment of $ " + invoice.getPayment_balance() + " will reach us within 30 days. </p> <p> If you have doubt with your bill and payment, Please contatct us \n\n Thanks For having Business With Us!</p> <p> \n\nYour Sincerely, \n MerlionFood Limited";
        }
        if (dunningEmail.getPatternId() == 3) {
            fillContent = "<p>Dear Customer " + invoice.getDeliveryOrder().getParentSalesOrder().getCustomer().getName() + ":</p> <p>This is a dunning email for your Bill : " + invoice.getId() + "</p> <p> Please understand that this is our final notice to you. However, we give you one last opportunity to clear the account within 30 days from the date we send you this email. </p> <p> After this date it is our normal policy to pass-on seriously delinquently accounts to a third party collection agency or our legal counsel. This could further jeopardize you credit rating in the industry.</p> <p>We trust that this will not be necessary. </p> <p> Once again this is our Final Notice. </p> <p>\n\n Your Sincerely, \n MerlionFood Limited";
        }
        return fillContent;

    }

    private Boolean checkInvoice(InvoiceEntity invoiceEntity) {
        Boolean isReady = false;
        if (invoiceEntity.getAmountPaid() >= invoiceEntity.getAmountPayable()) {
            isReady = false;
        } else {
            isReady = true;
        }
        return isReady;
    }

    public InvoiceEntity getInvoice() {
        return invoice;
    }

    public DunningEmailEntity getDunningEmail() {
        return dunningEmail;
    }

    public void setDunningEmail(DunningEmailEntity dunningEmail) {
        this.dunningEmail = dunningEmail;
    }

    public Long getInvoiceId() {
        return invoiceId;
    }

    public void setInvoiceId(Long invoiceId) {
        this.invoiceId = invoiceId;
    }

    public void setInvoice(InvoiceEntity invoice) {
        this.invoice = invoice;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}
